import {
  postCategoryAdd,
  getRoleList,
  getUserQuery,
  getCategoryGetAuthorities,
  postCategoryAddAuthorities,
  postCategoryRename
} from '@/api';
import { MciButton, MciDialog, MciInput, MciNotification, MciSelect } from '@/components/base';
import { ElForm, ElFormItem } from 'element-plus';
import { ADMIN_ROLECODE } from '@/constants/config';

export const AddMenuDecision = defineComponent({
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: ''
    },
    categoryId: {
      type: String,
      default: ''
    },
    categoryName: {
      type: String,
      default: ''
    }
  },
  emits: ['update:modelValue', 'refreshList'],
  setup(props, { emit }) {
    const params = ref({} as any);
    const loading = ref(false);
    const formRef = ref<InstanceType<typeof ElForm>>();
    const modelInput = ref([] as any);
    const optionList = ref({} as any);

    const confirmHandle = async () => {
      try {
        await formRef.value?.validate();
        loading.value = true;
        const roleUsers: any[] = [];
        for (const item of modelInput.value) {
          if (params.value[item.value] && params.value[item.value].length > 0) {
            roleUsers.push({
              roleId: item.value,
              accountNames: params.value[item.value]
            });
          }
        }
        if (props.title === '新增目录') {
          // 构建最终要提交的数据
          const data = {
            categoryName: params.value.categoryName,
            icon: '',
            roleUsers
          };
          postCategoryAdd(data)
            .then(() => {
              emit('refreshList');
              handleClose();
              MciNotification.success({ title: '操作成功' });
            })
            .catch(() => {});
        } else if (props.title === '修改目录') {
          // 构建最终要提交的数据
          const data = {
            categoryId: props.categoryId,
            icon: '',
            roleUsers
          };
          postCategoryAddAuthorities(data)
            .then(() => {
              emit('refreshList');
              handleClose();
              MciNotification.success({ title: '操作成功' });
            })
            .catch(() => {});
        } else if (props.title === '重命名') {
          postCategoryRename({ categoryId: props.categoryId, categoryName: params.value.categoryName }).then(() => {
            emit('refreshList');
            handleClose();
            MciNotification.success({ title: '操作成功' });
          });
        }
      } catch (error) {
      } finally {
        loading.value = false;
      }
    };

    const handleClose = () => {
      emit('update:modelValue', false);
    };

    // 根据角色获取用户列表
    const getUserList = async (roleCode: string) => {
      const res = await getUserQuery({ roleCode });
      if (res) {
        const list =
          res?.map((item: any) => {
            return {
              value: item.accountName,
              label: item.username
            };
          }) || [];
        optionList.value = {
          ...optionList.value,
          [roleCode]: list
        };
      }
    };

    // 获取角色
    const getInitData = async () => {
      const res = await getRoleList({ flowId: props.flowId });
      if (res) {
        modelInput.value =
          res
            ?.filter((item) => Number(item.roleCode) !== ADMIN_ROLECODE)
            ?.map((item: any) => {
              getUserList(item.roleCode);
              return {
                value: item.roleCode,
                label: item.roleName
              };
            }) || [];
      }
    };

    // 修改目录-审批人默认值
    const defaultParams = async () => {
      const res = await getCategoryGetAuthorities({ categoryId: props.categoryId });
      if (res) {
        // 转换数据结构
        const convertedData = {
          ...res.reduce((acc, curr) => {
            acc[curr.roleId] = curr.accountNames;
            return acc;
          }, {})
        };
        params.value = convertedData;
        params.value.categoryName = props.categoryName;
      }
    };

    watch(
      () => props.modelValue,
      (val) => {
        if (!val) {
          formRef.value?.resetFields();
        } else {
          getInitData();
          if (props.title === '修改目录' || props.title === '重命名') {
            defaultParams();
          }
        }
      }
    );

    return () => (
      <>
        <MciDialog
          title={props.title}
          confirmHandle={confirmHandle}
          v-model={props.modelValue}
          width={500}
          onClose={handleClose}
          customClass="max-height-dialog">
          {{
            default() {
              return (
                <ElForm ref={formRef} model={params.value} labelPosition="top">
                  <ElFormItem
                    label={props.title === '重命名' ? '新目录名称' : '目录名称'}
                    prop="categoryName"
                    rules={[
                      {
                        required: true,
                        message: `请输入目录名称`,
                        trigger: ['change', 'blur']
                      }
                    ]}>
                    <MciInput
                      placeholder="请输入"
                      v-model={params.value.categoryName}
                      disabled={props.title === '修改目录'}
                      maxlength={10}
                    />
                  </ElFormItem>
                  {props.title !== '重命名' &&
                    modelInput.value?.map((item: any) => {
                      // 确保params.value[item.value]存在并初始化为空数组
                      if (!params.value[item.value]) {
                        params.value[item.value] = [];
                      }
                      return (
                        <ElFormItem
                          label={item.label}
                          prop={item.value}
                          rules={[
                            {
                              required: true,
                              message: `请输入${item.label}`,
                              trigger: ['change', 'blur']
                            }
                          ]}>
                          <MciSelect
                            class="w-full"
                            v-model={params.value[item.value]}
                            clearable
                            filterable
                            multiple
                            list={optionList.value[item.value]}
                            placeholder="请选择"
                          />
                        </ElFormItem>
                      );
                    })}
                </ElForm>
              );
            },
            footer() {
              return (
                <>
                  <MciButton onClick={handleClose} disabled={loading.value}>
                    取消
                  </MciButton>
                  <MciButton type="primary" onClick={confirmHandle} disabled={loading.value}>
                    确定
                  </MciButton>
                </>
              );
            }
          }}
        </MciDialog>
      </>
    );
  }
});
